#!/bin/bash

kp=android
alias=key
keysize=512

current=`pwd`

#RSA-keysize signature-length
# 512        64
# 1024       128
# 2048       256

mkdir -p .tmp
rm -rf .tmp/ks
keytool -genkeypair -dname "CN=Test" -keyalg RSA -keysize $keysize -keystore .tmp/ks -keypass $kp -validity 365 -storepass $kp  -alias $alias


privateKey=`java -cp ~/.m2/repository/commons-codec/commons-codec/1.6/commons-codec-1.6.jar:target/test-classes pxb.android.tinysign.gen.PrivateKey .tmp/ks $kp $alias $kp`

cd .tmp
echo "qwert" > tmp.txt
rm -rf a.jar > /dev/null
jar cfM a.jar tmp.txt > /dev/null

jarsigner -sigalg sha1withrsa -digestalg sha1 -keystore ks -storepass $kp  a.jar $alias

rm -rf META-INF/${alias^^}.RSA
jar xf a.jar > /dev/null

set -- `du -b META-INF/${alias^^}.RSA`
size=$1

sigsize=0
case $keysize in
512)
sigsize=64
;;
1024)
sigsize=128
;;
2048)
sigsize=256
;;
*)
echo "not support keysize $keysize"
exit -1
;;
esac
sigPrefix=`dd if=META-INF/${alias^^}.RSA bs=1  count=$(($size-$sigsize)) | base64 -w 0`

cd $current

echo "
// generated by script gen.sh
package pxb.android.tinysign;

public interface Constants {
    String privateKey = \"$privateKey\";
    String sigPrefix = \"$sigPrefix\";
}
" > src/main/java/pxb/android/tinysign/Constants.java

echo Done.
